package com.tencent.wework.list

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.*
import kotlinx.android.synthetic.main.base_list_fragment.*


/**
 * Created by huangwei on 2019/5/27.
 */
abstract class BaseListFragment():Fragment(){

    lateinit var adapter:LmAdapter
    protected var enableLoadMore = true
    protected var hasMoreData = true
    private lateinit var onScrollListener :RecyclerView.OnScrollListener

    protected var loadMoreDirection = LoadMoreDirection.BOTTOM
    protected var viewpagerMode = false
    /**
     * 加载更多时，滑动到离边界还有5个item时，开始加载更多
     */
    protected var PRELOAD_SIZE = 5

    private fun addListener() {
        onScrollListener = object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (dy != 0 || dx != 0) {
                    checkLoadMore()
                }
            }
        }
        recyclerView.addOnScrollListener(onScrollListener)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.base_list_fragment,container,false)
    }

    open fun initData(){
        onDataRefresh()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initRecyclerView()
        addListener()
        initData()
    }

    open fun initAdapter():LmAdapter{
        return LmAdapter()
    }
    open fun initRecyclerView(){
        recyclerView.layoutManager = LinearLayoutManager(activity)
        adapter = initAdapter()
        recyclerView.adapter = adapter
        if(viewpagerMode){
            val snapHelper = PagerSnapHelper()
            snapHelper.attachToRecyclerView(recyclerView)
        }
    }

    protected abstract fun onDataRefresh()

    protected abstract fun onLoadMore()

    private fun checkLoadMore() {
        if (!enableLoadMore ||  adapter.isEmpty() || adapter.isLoadingMore() || adapter.isEmpty() || adapter.isError() || adapter.isRefreshing()
            || adapter.isNoMoreShowing() || !hasMoreData
        ) {
            return
        }

        val layoutManager = recyclerView.layoutManager
        var shouldLoadMore = false
        when(loadMoreDirection){
            LoadMoreDirection.BOTTOM ->{
                if (layoutManager is LinearLayoutManager) {
                    shouldLoadMore = layoutManager.findLastVisibleItemPosition() >= adapter.itemCount - 1 - PRELOAD_SIZE
                } else if (layoutManager is GridLayoutManager) {
                    shouldLoadMore =
                        layoutManager.findLastVisibleItemPosition() >= adapter.itemCount - 1 - PRELOAD_SIZE * layoutManager.spanCount
                } else if (layoutManager is StaggeredGridLayoutManager) {
                    val items = layoutManager.findLastVisibleItemPositions(null)
                    val last =
                        adapter.itemCount - 1 - PRELOAD_SIZE * layoutManager.spanCount
                    for (i in items.indices) {
                        if (items[i] >= last) {
                            shouldLoadMore = true
                            break
                        }
                    }
                }
            }
            LoadMoreDirection.TOP ->{
                if (layoutManager is LinearLayoutManager) {
                    shouldLoadMore = layoutManager.findFirstVisibleItemPosition() <= PRELOAD_SIZE
                } else if (layoutManager is GridLayoutManager) {
                    shouldLoadMore =
                        layoutManager.findLastVisibleItemPosition() <= PRELOAD_SIZE * layoutManager.spanCount
                } else if (layoutManager is StaggeredGridLayoutManager) {
                    val items = layoutManager.findLastVisibleItemPositions(null)
                    val last = PRELOAD_SIZE * layoutManager.spanCount
                    for (i in items.indices) {
                        if (items[i] <= last) {
                            shouldLoadMore = true
                            break
                        }
                    }
                }
            }
        }

        if (shouldLoadMore) {
            adapter.showLoadingMore(loadMoreDirection)
            onLoadMore()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        recyclerView.removeOnScrollListener(onScrollListener)
        adapter.onDestroyView()
    }

}

enum class LoadMoreDirection{
    BOTTOM,
    TOP
}